import { View, Text } from '@tarojs/components';
import { useState, useEffect } from 'react';
import { getUser } from '@/utils/user';
import './index.less';
import request from '@/utils/request';

interface IRecord {
  id: string;
  userId: string;
  consumProject: string; // 消耗项目
  consumAmount: number; // 消耗额度
  surplusAmount: number; // 剩余额度
  createTime: string; // 创建时间
}

export default function Index() {
  const user = getUser();
  const [records, setRecords] = useState<IRecord[]>([]);

  useEffect(() => {
    fetchRecords();
  }, []);

  const fetchRecords = async () => {
    // TODO: 调用后端接口
    const res = await request.get<IRecord[]>('/token-consum/query', {
      userId: user.id,
    });
    console.log('res', res);
    setRecords(res);

    // 模拟数据
    // setRecords([
    //   {
    //     id: '1',
    //     userId: '1',
    //     consumProject: '创建视频',
    //     consumAmount: 100,
    //     surplusAmount: 100,
    //     createTime: '2024-03-20 12:00:00'
    //   },
    //   {
    //     id: '2',
    //     userId: '1',
    //     consumProject: '创建视频',
    //     consumAmount: 100,
    //     surplusAmount: 200,
    //     createTime: '2024-03-20 12:00:00'
    //   }
    // ]);
  };

  return (
    <View className="consumption-record">
      <View className="balance-card">
        <View className="label">当前剩余</View>
        <View className="amount">{user?.token|| 0}<Text className="unit">cc</Text></View>
      </View>

      <View className="record-list">
        {records.map(record => (
          <View key={record.id} className="record-item">
            <View className="record-info">
              <View className="record-title">{record.consumProject}</View>
              <View className="record-type">{"剩余：" + record.surplusAmount}</View>
              <View className="record-time">{record.createTime}</View>
            </View>
            <View className={`record-amount ${record.consumAmount > 0 ? '' : 'record-amount-green'}`}>
              {-Number(record.consumAmount).toFixed(2)}<Text className="unit">cc</Text>
            </View>
          </View>
        ))}
      </View>
    </View>
  );
}
